package com.dys.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: 疾风
 * @ClassName: RequestLogListener
 * @Description: 监听器：记录每次请求中如下的信息并存储进入日志文件，请求的来源，浏览器所在电脑IP，请求的资源 URL，请求发生的时间
 * @CreateDate: 2024/09/25
 * @Version: v1.0.0
 */
@WebListener
public class RequestLogListener implements ServletRequestListener {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("请求监听器销毁");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 1.获得请求发出的IP 2.获得请求的URL 3.获得请求产生的时间 4.准备输出流
        HttpServletRequest httpServletRequest = (HttpServletRequest) sre.getServletRequest();
        String remoteHost = httpServletRequest.getRemoteHost();
        String requestUrl = httpServletRequest.getRequestURL().toString();
        String requestDate = simpleDateFormat.format(new Date());
        // 4.准备输出流
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(new FileOutputStream(new File("d:/listener.txt"), true));
            printWriter.println("主机：" + remoteHost + ",请求URL: " + requestUrl + ", 请求时间：" + requestDate);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }
}
